// pages/buycoupon/buycoupon.js
const host = require('../../config.js').host;
const network = require('../../utils/network.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    couponList: [],
    selectIndex: 0,
    price: 0,
    banlance: 0,
  },
  getBanlance() {
    let that = this;
    network.requestGet(host + '/xcx/customer/getUserInfo', {}, res => {
      if (res.data.code == 200) {
        that.setData({
          banlance: res.data.data.balance,
        })
      }
    })
  },
    // 根据卡位码支付
    getCouponList() {

      let that = this; 
      network.requestGet(host + '/xcx/goodsCard/list', {
        
      }, res => {
  
        if (res.data.code == 200) {
          that.setData({
            couponList:res.data.rows
          })
          
          if(that.data.selectIndex==0){
            // let selectIndex = that.data.selectIndex
            that.setData({
              price:res.data.rows[0].price
            })
            
          }
        } else {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '请求失败',
            icon: "none",
            duration: 1200
          })
        }
      })
    },
  selectIndexClick(e) {
    let couponList = this.data.couponList
    let selectIndex = this.data.selectIndex
    let price = this.data.price
    this.setData({
      selectIndex: e.currentTarget.dataset.index,
      price: couponList[e.currentTarget.dataset.index].price
    });

  },
  chosePayType(){

    let that=this;
    wx.showActionSheet({
      itemList: ['余额支付', '微信支付'],
      success: function (res) {
        console.log("点击了列表项：" + res.tapIndex)
        if (res.tapIndex == 0) {
          that.postPayData(true);
        } else if (res.tapIndex == 1) {
          that.postPayData(false);
        }
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },
  
  gotoquestion() {
    wx.navigateTo({
      url: '/pages/question/question',
    })
  },
  // 根据支付类型 支付
  postPayData(isBanlance) {

    let that = this; 
    if (isBanlance) { 

      // console.log("遍历结束")
      // debugger


      if (that.data.price > that.data.banlance) {

        wx.showModal({
          title: '提示',
          content: '余额不足,是否去充值?',
          showCancel: true, //是否显示取消按钮
          cancelText: "取消", //默认是“取消”
          cancelColor: '#ff0000', //取消文字的颜色
          confirmText: "确定", //默认是“确定”
          confirmColor: '#000000', //确定文字的颜色
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定
              wx.navigateTo({
                url: '/pages/recharge/recharge',
              })
            }
          },
          fail: function (res) {},
          complete: function (res) {},
        })

        return;
      }
      wx.showModal({
        title:'是否支付' +that.data.price+ '元?',
        content: '当前账户余额:' + that.data.banlance + '元',
        showCancel: true, //是否显示取消按钮
        cancelText: "取消", //默认是“取消”
        cancelColor: '#ff0000', //取消文字的颜色
        confirmText: "确定", //默认是“确定”
        confirmColor: '#000000', //确定文字的颜色
        success(res) {
          if (res.confirm) {
            
            network.requestPost(host + '/weiXinPayment/buyGoodsCard', {
              "goodsCardId":that.data.couponList[that.data.selectIndex].goodsCardId,
              "buyCount ": "1",
              "balancePay": isBanlance
            }, res => {
              console.log("根据卡位码支付=" + res)
              if (res.data.code == 200) {
                that.gotosuccess()
              } else {
                wx.showToast({
                  title: res.data.msg ? res.data.msg : '请求失败',
                  icon: "none",
                  duration: 2000
                })
              }
            })
          } else if (res.cancel) {
            return;
          }
        }
      })


    } else {
      
      network.requestPost(host + '/weiXinPayment/buyGoodsCard', {
        "goodsCardId":that.data.couponList[that.data.selectIndex].goodsCardId,
        "buyCount ": "1",
        "balancePay": isBanlance
      }, res => {
        

        if (res.data.code == 200) {
          if (res.data.h5PayArgs) {
            that.gotopay(res.data.h5PayArgs)
          }  
        } else {
          wx.showToast({
            title: res.data.msg ? res.data.msg : '请求失败',
            icon: "none",
            duration: 2000
          })
        }
      })
    }
  },
  gotosuccess(){
    wx.showToast({
      title: '支付成功',
      duration: 2000
    })
    setTimeout(() => {
      wx.navigateBack({
        delta: 0,
      })
    
    }, 2000);
    
  },
  gotopay(e) {
    let that = this;

    wx.requestPayment({
      signType: e.signType,
      timeStamp: e.timeStamp,
      nonceStr: e.nonceStr,
      package: e.package,
      paySign: e.paySign,
      success(res) {
        that.gotosuccess()
      },
      fail(res) {
        console.log('失败：' + res)
        wx.showToast({
          title: '支付失败',
          duration: 3000
        })
      },
      complete(res) {

      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getCouponList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getBanlance();

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})